<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Integralproduct as IntegralproductMdl;
use app\admin\model\Integralrecord;
use app\admin\model\Member;
use app\admin\model\CouponProduct;
use app\admin\model\CouponProductCategory;
use app\admin\model\Productcategory;
use app\admin\model\MessageNotice;
use app\api\service\Message as MessageService;

use think\Db;
use think\Exception;

class Integralproduct extends Base
{

    /**
     * 首页数据
     */
    public function home()
    {
        $param = self::getHttpParam();
        $where = [];

        // 积分规则
        $integralRule = $this->getIntegralRule($where);

        // 积分商城
        $integralRroduct = $this->getIntegrals($where, 'a.create_date DESC', 0, 2);

        $data = [
            'integralRule' => $integralRule ? : '',
            'integralRroduct' => $integralRroduct ? : '',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    // 获取积分规则
    protected function getIntegralRule($where)
    {
        $model = db('integral_rule');
        $field = 'open_member, perfect_info, comment, description';
        $result = $model->where($where)->field($field)->find();
        if (!$result) {
            return [];
        }

        return $result;
    }

    // 获取积分
    protected function getIntegrals($where, $order, $start, $length)
    {
        $model = new IntegralproductMdl();
        $where['a.status'] = 1;
        $where['b.number'] = ['gt', 0]; // 优惠券数量大于0
        $where['b.end_time'] = ['gt', date('Y-m-d H:i:s',time())]; // 优惠券未过期
        $fields = 'a.id, a.img_url, a.coupon_id, a.exchange_num, a.content, b.coupon_type, b.cash_amount, b.discount_strength, b.threshold';
        $list = $model->alias('a')->where($where)->join('__COUPON__ b', 'b.id = a.coupon_id')->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return [];
        }

        foreach ($list as &$item) {
            //$coupon = Coupon::where('id', $item['coupon_id'])->find();
            $item = $this->formatIntegral($item);
        }

        return $list;
    }

    /**
     * 积分商城列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        $where = [];
        $list = $this->getIntegrals($where, 'a.create_date DESC', $start, $length);
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '没有相关积分兑换', '没有相关积分兑换');
        }
        $total = IntegralproductMdl::alias('a')->where($where)->where(['a.status' => 1, 'b.number' => ['gt', 0]])->join('__COUPON__ b', 'b.id = a.coupon_id')->count();

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 积分详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '积分ID(id) 不能为空');
        }

        $integralId = $param->id;
        $where = [
            'a.id' => $integralId
        ];
        $model = new IntegralproductMdl();
        $fields = 'a.id, a.img_url, a.coupon_id, a.exchange_num, a.content, b.coupon_type, b.cash_amount, b.discount_strength, b.threshold, b.start_time, b.end_time';
        $item = $model->alias('a')->where($where)->join('__COUPON__ b', 'b.id = a.coupon_id')->field($fields)->find();
        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), '未查到相关积分', '未查到相关积分');
        }

        $item = $this->formatIntegral($item);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 兑换积分
     */
    public function exchange()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->integralId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '积分ID(integralId) 不能为空');
        }
        if (empty($param->couponId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '优惠券ID(couponId) 不能为空');
        }
        if (empty($param->exchangeNum)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '兑换积分(exchangeNum) 不能为空');
        }

        Db::startTrans();
        try {
            $memberInfo = Member::where('id', $param->memberId)->field('integral, c_id')->find();
            if($memberInfo['integral'] < $param->exchangeNum){
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '您的积分不足，不能兑换');
            }

            $model = new Integralrecord();
            $data = [
                'create_date' => date('Y-m-d H:i:s'),
                'order_no' => BaseHelper::getUUID(),
                'integral_id' => $param->integralId,
                'coupon_id' => $param->couponId,
                'member_id' => $param->memberId,
                'num' => 1,
                'exchange_num' => $param->exchangeNum,
                'type' => 2,
                'source' => '兑换超级券', // TODO 用文字，还是数字来代替？
            ];
            // 添加兑换记录
            $result = $model->save($data);

            if($result !== false){
                // 会员减去相应的积分
                $res = Member::where('id', $param->memberId)->setDec('integral', $param->exchangeNum);
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '兑换失败');
                }
                // 添加优惠券
                $couponData = [
                    'id' => BaseHelper::getUUID(),
                    'create_date' => date('Y-m-d H:i:s'),
                    'member_id' => $param->memberId,
                    'coupon_id' => $param->couponId,
                    //'status' => 1
                ];
                $couponRes = \app\admin\model\Membercoupon::insert($couponData);
                if($couponRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '添加优惠券失败');
                }
                // 兑换数量 +1
                IntegralproductMdl::where('id', $param->integralId)->setInc('use_num');
                // 统计 兑换人数 TODO

                /*
                // 添加账户通知消息
                $messageData = [
                    'create_date' => date('Y-m-d H:i:s'),
                    'member_id' => $param->memberId,
                    'img_url' => '',
                    'title' => '您的积分有了变化',
                    'detail' => '您花费了' . $param->exchangeNum . '积分，兑换了一张超级券',
                    'type' => 2
                ];
                $messageRes = MessageNotice::insert($messageData);
                if($messageRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '添加账户通知消息失败');
                }
                */

                // 添加账户通知消息 -- 获得优惠券
                $couponMesData = [
                    'create_date' => date('Y-m-d H:i:s'),
                    'member_id' => $param->memberId,
                    'img_url' => '',
                    'title' => '您获得了优惠券',
                    'detail' => '您获得了1张优惠券，点击立即使用',
                    'type' => 1,
                ];
                $couponMesRes = MessageNotice::insert($couponMesData);
                if($couponMesRes === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '添加优惠券账户通知消息失败');
                }

                // 推送送APP消息
                $mesData = [
                    'template_type' => 1,
                    'template_data' => [
                        'transmission_type' => 1,
                        'transmission_content' => '',
                        'title' => '您获得了优惠券',
                        'text' => '您获得了1张优惠券，点击立即使用',
                        'logo'  => '',
                        'logo_url'  => '',
                    ],
                    'cid' => $memberInfo['c_id'], // 推送通知至指定用户时填写
                    'cid_list' => '', // 推送通知至指定用户列表时填写
                ];
                MessageService::pushNotice($mesData);

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '开通成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 积分明细
     */
    public function getRecords()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }

        $where = [
            'member_id' => $param->memberId,
        ];

        $model = new Integralrecord();
        $fields = '*';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($fields)->order($order)->select();
        if(!$list){
            return show(config('status.ERROR_STATUS'), '没有积分明细', '没有积分明细');
        }

        $total = $model->where($where)->count();

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    // 格式化积分信息
    protected function formatIntegral($item){
        if(!$item){
            return '';
        }

        // 优惠券类型
        $item['coupon_type_name'] = show_coupon_type($item['coupon_type']);
        $item['name'] = $item['coupon_type_name'];
        // 品类券
        if($item['coupon_type'] == 2 || $item['coupon_type'] == 5){
            $categoryIds = CouponProductCategory::where(['coupon_id' => $item['coupon_id']])->value('category_id');
            $item['product_category'] = Productcategory::where(['id' => ['in', $categoryIds]])->field('id, name')->select();
        }
        // 单品券
        if($item['coupon_type'] == 3 || $item['coupon_type'] == 6){
            $item['coupon_product'] = CouponProduct::alias('a')->where(['a.coupon_id' => $item['coupon_id']])->join('__PRODUCT__ b', 'b.id = a.product_id')->field('b.id, b.name')->find();
        }

        return $item;
    }

    //消费送积分
    public static function consumptiongiveintegral($member_id,$total,$order_id=NULL,$type=1){
        $giveintegral = 0;
        $Member = Member::where('id',$member_id)->find();
        $member_level_id = $Member->member_level_id;
        $Memberlevel = \app\admin\model\Memberlevel::where('id',$member_level_id)->find();
        if($member_level_id == 1){
            if($Memberlevel->is_gives_points == 1){
                $giveintegral = intval($total*$Memberlevel->integral_quantity/100);
            }
        }else{
            $level_end_time = strtotime($Member->level_end_time);
            if($Memberlevel->is_gives_points == 1 && time()<$level_end_time){
                $giveintegral = intval($total*$Memberlevel->integral_quantity/100);
            }
        }
        if($giveintegral >0){
            if($type == 2){
                \app\admin\model\Order::where('id',$order_id)->update(['send_points'=>$giveintegral]);
                //会员增加积分
                $Member->setInc('integral',$giveintegral);
                //增加积分记录
                $Integralrecord = new Integralrecord();
                $Integralrecord->order_no = $order_id;
                $Integralrecord->member_id = $member_id;
                $Integralrecord->type = 1;
                $Integralrecord->source = '消费送积分';
                $Integralrecord->exchange_num = $giveintegral;
                $Integralrecord->save();
            }
        }
        if($type == 1){
            return show(config('status.SUCCESS_STATUS'),'ok',$giveintegral);
        }
    }

}